#coding=utf-8
#LightCam oracle监控程序
#init by hfh 20150319

import multiprocessing,subprocess
import socket,os,time,re,traceback,sys
import lc_libs
import cx_Oracle

def func(agent_hostname,dbname,sqlname,alertflag,interval,severity,schedule,holiday):
	while True:
		try:
			Node=agent_hostname
			AlertGroup="BizTrdVcsCheck"
			AlertKey=dbname+"-"+sqlname
			Summary=""
			Severity=0
			Type=0
		
			#判断时间策略
			tempflags=lc_libs.lc_schedule(schedule)
			if tempflags==False:
				time.sleep(int(interval))
				continue
			#判断节假日
			holiday_state=0
			if int(holiday)==1:
				if lc_libs.lc_isholiday():
					holiday_state=1
			if holiday_state==1:
				time.sleep(int(interval))
				continue
				
			sqlfile=open(sqlname,'r')
			sqlstr=sqlfile.read()
			
			dbcon=None
			try:
				dbcon=cx_Oracle.connect("cffex/biz_pass_0908@"+dbname)
				#dbcon=cx_Oracle.connect("cffex/biz_pwd_0522@"+dbname)
			except Exception:
				excinfo=traceback.format_exc()
				print excinfo
				continue
			
			cursor=dbcon.cursor()
			cursor.execute(sqlstr)
			
			if 'checkvcs' in sqlname:
				count=0
				for organname,userid,loginstatus,lastlogindate,lastlogintime,servicename in cursor.fetchall():
					strs="机构名称:"+organname.decode('gbk').encode('utf-8')+",用户ID:"+userid.decode('gbk').encode('utf-8')+",登录状态:"+loginstatus.decode('gbk').encode('utf-8')+",登录日期:"+lastlogindate.decode('gbk').encode('utf-8')+",登录时间:"+lastlogintime.decode('gbk').encode('utf-8')+",登录前置:"+servicename.decode('gbk').encode('utf-8')
					print strs.decode('utf8').encode('gbk')
					count=count+1
				print "当前用户登录数：".decode('utf8').encode('gbk')+str(count)
					
		except Exception:
			excinfo=traceback.format_exc()
			print excinfo
			logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
			logfile.write(logdate+" :\n"+excinfo+"\n")
			logfile.flush()
			time.sleep(1)
			break
		break
		time.sleep(int(interval))

if __name__ == "__main__":

	lchome=lc_libs.lc_getlchome()
	scname=sys.argv[0].split('.')[0]
	logfilename=lchome+'/log/'+scname+'.log'
	confname=lchome+'/conf/'+scname+'.conf'
	
	#today=time.strftime('%Y%m%d',time.localtime())
	#os.system("mv %s %s.%s" % (logfilename,logfilename,today))
	
	logfile=file(logfilename,'a')
	logdate=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
	logfile.write(logdate+" Started.\n")
	logfile.flush()
	#logfile.close()
	
	agent_hostname=lc_libs.lc_gethostname()

	#主程序
	for line in open(confname):
		#if line[0] == '#' or agent_hostname != line.split("\t")[0]:
		if line[0] == '#' or line.split("\t")[0] not in (agent_hostname,'default'):
			continue
		dbname=line.strip('\n').split("\t")[1]
		sqlname=lchome+'/sql/'+line.strip('\n').split("\t")[2]+'.sql'
		alertflag=float(line.strip('\n').split("\t")[3])
		interval=line.strip('\n').split("\t")[4]
		severity=line.strip('\n').split("\t")[5]
		schedule=line.strip('\n').split("\t")[6]
		holiday=line.strip('\n').split("\t")[7]
		
#		pool = multiprocessing.Pool(processes=1)
#		result.append(pool.apply_async(func, (agent_hostname,dbname,sqlname,alertflag,interval,severity,schedule,holiday)))
		func(agent_hostname,dbname,sqlname,alertflag,interval,severity,schedule,holiday)

